﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using com.jwxcd.CommunityDriver;
using PersonalHealth.Data.Model;
using PersonalHealth.Data.IService;
using PersonalHealth.Data.Service;
using System.Threading;

namespace PersonHealth.View
{
    /// <summary>
    /// BloodSugar.xaml 的交互逻辑
    /// </summary>
    public partial class BloodSugar : MeasureBase
    {
        private int status = 0;
        IList<Threshold> thresholds;
        public BloodSugar()
        {
            InitializeComponent();
        }
        //开始测量
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            status += 1;
            switch (status)
            {
                case 0:
                    break;
                case 1:
                    stepOneGrid.Visibility = Visibility.Collapsed;
                    finalStepGrid.Visibility = Visibility.Visible;
                    btnNext.Text = "开始测量";
                    break;
                case 2:
                    Query.Visibility = Visibility.Hidden;
                    DoMeasure.Visibility = Visibility.Hidden;
                    finalStepGrid.Visibility = Visibility.Collapsed;
                    testStepGrid.Visibility = Visibility.Visible;

                    Dispatcher.BeginInvoke(
                        new Action(
                          () =>
                          {
                              connectTimer = new DispatcherTimer();
                              connectTimer.Interval = new TimeSpan(10000000);
                              connectTimer.Tick += new EventHandler(connectTimer_Tick);
                              connectSecondsCount = 0;
                              connectTimer.Start();
                          }
                        )
                    );
                    driver.connect();
                    break;
                default:
                    break;
            }
        }

        DispatcherTimer connectTimer;
        int connectSecondsCount = 0;
        void connectTimer_Tick(object sender, EventArgs e)
        {
            connectSecondsCount++;
            connectDown.Text = (30 - connectSecondsCount).ToString();
            if (connectSecondsCount == 30)
            {
                DispatcherTimer timer = sender as DispatcherTimer;
                timer.Stop();

                OnError("连接设备超时，请返回重试！");
            }
        }

        //查看趋势
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //NavigationService.Navigate(new Uri("View/BloodSugarList.xaml", UriKind.RelativeOrAbsolute));
            NavigationService.Content = new BloodSugarList();
        }

        public override void onDriverConnected(object sender, EventArgs e)
        {
            Thread.Sleep(500);
            Dispatcher.Invoke(new Action(
               () =>
               {
                   if (connectTimer != null)
                       connectTimer.Stop();
                   testStepStack.Visibility = Visibility.Collapsed;
                   testStepStack1.Visibility = Visibility.Visible;

                   IUserService service = new UserService();
                   thresholds = service.GetThreshold("BG", AppData.User.Id);
               }));

        }

        bool flag = false;
        public override void onMeasure(object sender, MeasureEventArgs e)
        {

            if (!flag && e.value.Glucose != 0)
            {
                flag = true;
                Dispatcher.Invoke(new Action(
                   () =>
                   {
                       if (resultStepGrid.Visibility == Visibility.Collapsed)
                       {
                           testStepGrid.Visibility = Visibility.Collapsed;
                           resultStepGrid.Visibility = Visibility.Visible;
                       }
                       Save.Visibility = Visibility.Visible;
                       Cancel.Visibility = Visibility.Visible;

                       saveTimer = new DispatcherTimer();
                       saveTimer.Interval = new TimeSpan(10000000);
                       saveTimer.Tick += new EventHandler(saveTimer_Tick);
                       saveSecondsCount = 0;
                       saveTimer.Start();

                       countDownInfo.Visibility = Visibility.Visible;

                       //血糖
                       BloodGlucose.Text = e.value.Glucose.ToString();
                       foreach (var i in thresholds)
                       {
                           if (i.MeasureSubType.Code == "BloodGlucose")
                           {
                               if (e.value.Glucose < i.Min || e.value.Glucose > i.Max)
                               {
                                   bgPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff8700")) as Brush;
                               }
                               else
                               {
                                   bgPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6D9700")) as Brush;
                               }
                           }
                       }

                       countDownInfo.Visibility = Visibility.Visible;
                   }
                ));

            }
        }

        DispatcherTimer saveTimer;
        int saveSecondsCount = 0;
        void saveTimer_Tick(object sender, EventArgs e)
        {
            saveSecondsCount++;
            seconds.Text = (10 - saveSecondsCount).ToString();
            if (saveSecondsCount == 10)
            {
                DispatcherTimer timer = sender as DispatcherTimer;
                timer.Stop();
                Save.IsEnabled = false;
                Cancel.IsEnabled = false;
                save();
                Save.IsEnabled = true;
                Cancel.IsEnabled = true;

                OnNotice("测试数据已自动保存！");
            }
        }

        //保存
        private void Save_Click(object sender, RoutedEventArgs e)
        {

            if (saveTimer != null)
                saveTimer.Stop();
            save();
            NavigationService.GoBack();
        }

        //取消
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (saveTimer != null)
                saveTimer.Stop();
            NavigationService.GoBack();
        }


        public override void MeasureBase_Unloaded(object sender, RoutedEventArgs e)
        {
            if (saveTimer != null)
                saveTimer.Stop();
            if (connectTimer != null)
                connectTimer.Stop();
            base.MeasureBase_Unloaded(sender, e);
        }

        private void save()
        {
            double bloodGlucose;
            double.TryParse(BloodGlucose.Text, out bloodGlucose);
            Measure_BG obj = new Measure_BG();
            obj.UserId = AppData.User.Id;
            obj.BloodGlucose = bloodGlucose;
            DateTime now = DateTime.Now;
            obj.MeasureTime = obj.CreateDate = obj.ModifyDate = now;

            IMeasure_BGService ser = new Measure_BGService();
            ser.Add(obj);
        }
    }
}
